import { Layout, Form, Menu, Input, Icon, Checkbox, Button, Modal } from 'antd';
import { Link } from "react-router-dom";

import { Foot } from '../../components/Footer';
import './index.less';
const { Header, Content } = Layout;
const confirm = Modal.confirm;


class UI extends React.Component {
    constructor() {
        super();

        this.countDown = this.countDown.bind(this);
    }

    countDown() {
        let backurl = window.sessionStorage.getItem('backurl');

        let secondsToGo = 3;
        const modal = Modal.success({
            title: '登录成功!',
            content: `正在跳转请稍后 ${secondsToGo} s.`,
            onOk: () => {
                if (backurl) {
                    this.props.history.push(backurl);
                } else {
                    this.props.history.push('/home');
                }
            }
        });
        const timer = setInterval(() => {
            secondsToGo -= 1;
            modal.update({
                content: `正在跳转请稍后 ${secondsToGo} s.`,
            });
        }, 1000);
        setTimeout(() => {
            clearInterval(timer);
            if (backurl) {
                this.props.history.push(backurl);
            } else {
                this.props.history.push('/home');
            }
            modal.destroy();
        }, secondsToGo * 1000);
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let { userName, password } = values;
                // this.props.history.push('/home');

                let getUserArr = window.sessionStorage.getItem("user");

                if (getUserArr != null) {
                    getUserArr = JSON.parse(getUserArr);
                    let flag = 0;
                    // flag=0 用户不存在
                    // flag=1 密码错误
                    // flag=2 登陆成功
                    getUserArr.map(item => {
                        item.status = false;
                        if (item.name == userName) { // 找到该用户
                            if (item.pwd == password) {
                                item.status = true;
                                flag = 2; // 密码正确
                            } else {
                                flag = 1; // 密码不正确
                                return;
                            }
                        }
                    });

                    switch (flag) {
                        case 0:
                            Modal.error({
                                title: '错误提示!',
                                content: '该用户不存在:(',
                            });
                            break;
                        case 1:
                            Modal.error({
                                title: '错误提示!',
                                content: '密码错误:(',
                            });
                            break;
                        case 2:
                            // 将修改status的数组写回sessionStorage
                            window.sessionStorage.setItem('user', JSON.stringify(getUserArr));

                            this.countDown();
                            break;
                        default:
                            break;
                    }
                } else {
                    Modal.error({
                        title: '错误提示!',
                        content: '该用户不存在:(',
                    });
                }
            }
        });
    }

    render() {
        // getFieldDecorator 与表单进行双向绑定
        const { getFieldDecorator } = this.props.form;
        return (
            <div className="login form">
                <Layout>
                    <Header >
                        <div className="logo" />
                        <Menu
                            theme="dark"
                            mode="horizontal"
                            style={{ lineHeight: '64px' }}
                        >
                            <Menu.Item key="1">首页</Menu.Item>
                            <Menu.Item key="2">实体书</Menu.Item>
                            <Menu.Item key="3">电子书</Menu.Item>
                        </Menu>
                        <div className="header-r">
                            <p>欢迎来到必要，请 <Link to="/login">登录</Link> | <Link to="/register">注册</Link></p>
                        </div>
                    </Header>
                    <Content className="reg-form">
                        <Form onSubmit={this.handleSubmit} className="login-form">
                            <Form.Item>
                                {/* 参数一：表单唯一标识符 */}
                                {getFieldDecorator('userName', {
                                    rules: [{
                                        required: true,
                                        pattern: new RegExp(/^[0-9a-z_]{4,10}$/ig),
                                        message: '用户名需要4-10位且只包含数字字母下划线!'
                                    }],
                                })(
                                    <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="请输入用户名" />
                                )}
                            </Form.Item>
                            <Form.Item>
                                {getFieldDecorator('password', {
                                    rules: [{
                                        required: true,
                                        pattern: new RegExp(/^[0-9a-z_]{6,20}$/ig),
                                        message: '密码需要6-20位且只包含数字字母下划线!'
                                    }],
                                })(
                                    <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="请输入密码" />
                                )}
                            </Form.Item>
                            <Form.Item>
                                {getFieldDecorator('remember', {
                                    valuePropName: 'checked',
                                    initialValue: true,
                                })(
                                    <Checkbox>记住我</Checkbox>
                                )}
                                <a href="javascript:;">忘记密码?</a>
                                <Button type="primary" htmlType="submit" className="login-form-button">
                                    登录
                            </Button>
                                或 <Link to="/register">立即注册!</Link>
                            </Form.Item>
                        </Form>
                    </Content>
                    < Foot />
                </Layout>
            </div>
        );
    }
}

export const Login = Form.create({ name: 'normal_login' })(UI);